<!--
 * @Author: 王灿
 * @Date: 2019-11-10 16:10:08
 * @LastEditTime: 2020-04-18 13:22:51
 * @Description: 商品详情
 * @FilePath: \scarlet-sparrow-admin\src\views\commodity\commodity-details\index.vue
 -->
 <template>
  <div class="commodity-details">
    <happy-scroll color="rgba(0,0,0,0.05)" size="5" class="commodity-details__wrapper">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="el-form__details">
        <el-form-item prop="name">
          <el-input v-model="ruleForm.name" placeholder="商品名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="ruleForm.productAddress" clearable placeholder="商品产地">
            <el-option
              v-for="item in addressOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="ruleForm.type" clearable placeholder="商品类型" style="margin-right: 10px;">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-select v-model="ruleForm.upperShelfFlag" clearable placeholder="商品状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <div class="commodity-details__row">
          <el-form-item prop="markPrice">
            <el-input placeholder="标价" v-model="ruleForm.markPrice" clearable></el-input>
          </el-form-item>
          <el-form-item prop="actualPrice">
            <el-input placeholder="实际价格" v-model="ruleForm.actualPrice" clearable></el-input>
          </el-form-item>
          <el-form-item prop="stock">
            <el-input placeholder="商品库存" v-model="ruleForm.stock" clearable></el-input>
          </el-form-item>
        </div>
        <div class="commodity-details__row">
            <el-form-item prop="sales">
              <el-input placeholder="累计销量" v-model="ruleForm.sales" clearable></el-input>
            </el-form-item>
            <el-form-item prop="noVipRakeBack">
              <el-input placeholder="返佣金额" v-model="ruleForm.noVipRakeBack" clearable></el-input>
            </el-form-item>
            <el-form-item prop="selfPurchase">
              <el-input placeholder="自购省比例" v-model="ruleForm.selfPurchase" maxlength="4"></el-input>
            </el-form-item>
        </div>
        <el-form-item prop="introduce" class="el-form-textarea">
          <el-input
            type="textarea"
            maxlength="100"
            :autosize="{ minRows: 1, maxRows: 2}"
            placeholder="商品介绍"
            v-model="ruleForm.introduce"
          ></el-input>
        </el-form-item>
        <el-form-item prop="recommend ">
          <el-input type="textarea" :rows="2" placeholder="推荐理由" v-model="ruleForm.recommend " clearable></el-input>
        </el-form-item>
        <!-- 上传组件 -->
        <!-- 商品主图 -->
        <el-form-item>
          <jq-upload :upData="mainPicObj" :fileList="mainPic" @onChangeImageKey="onChangeImageKey" />
        </el-form-item>
        <!-- 详情主图 -->
        <el-form-item>
          <jq-upload :upData="detailPicObj" :fileList="detailPic" @onChangeImageKey="onChangeImageKey" />
        </el-form-item>
        <!-- 详情视频 -->
        <el-form-item>
          <upload-video
            :upData="detailVideoObj"
            :fileList="detailVideo"
            @onChangeImageKey="onChangeImageKey"
          />
        </el-form-item>
        <!-- 首页主图 -->
        <el-form-item>
          <jq-upload :upData="homePicObj" :fileList="homePic" @onChangeImageKey="onChangeImageKey" />
        </el-form-item>
      </el-form>
      <!-- 富文本 -->
      <div class="el-form__quill">
        <jq-tinymce
          ref="editor"
          v-model="ruleForm.detailsIntroduce"
          :isUpdate="isUpdate"
          :minHeight="1010"
          @input="onGetEditorValue"
        />
      </div>
    </happy-scroll>
    <div class="commodity-details__btns dialog-footer">
      <el-button type="primary" @click="onSubmitForm('ruleForm')">确 定</el-button>
      <el-button @click="onCancelForm('ruleForm')">取 消</el-button>
    </div>
  </div>
</template>

 <script>
import JqTinymce from '@/components/jq-tinymce/index.vue'
import JqUpload from '@/components/jq-upload/index.vue'
import UploadVideo from '@/components/upload-video/index.vue'
import {
  getProductAdd,
  getProductUpdate,
  getUploadKey,
  getDownUrl
} from '@/api/commodity.js'
import { Message } from 'element-ui'
export default {
  name: 'CommodityDetails',
  components: { JqUpload, JqTinymce, UploadVideo },
  props: {
    // 行数据
    row: {
      ttype: Object,
      default: () => {
        return {}
      }
    },
    // 商品产地
    addressOptions: {
      type: Array,
      default: []
    },
    // 商品类型
    commodityType: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      // 上传对象
      ruleForm: {
        id: '',
        name: '',
        productAddress: '',
        type: '',
        upperShelfFlag: 1,
        introduce: '',
        detailsIntroduce: '',
        mainPic: '',
        detailVideo: '',
        detailPic: '',
        homePic: '',
        markPrice: '',
        actualPrice: '',
        stock: '',
        sales: '',
        noVipRakeBack: '',
        selfPurchase: '',
        recommend: ''
      },
      defaultForm: {},
      // 商品主图
      mainPicObj: {
        label: '商品主图',
        accept: 'image/png, image/gif, image/jpg, image/jpeg',
        limit: 1,
        type: 1,
        isImage: true
      },
      // 商品详情主图
      detailPicObj: {
        label: '详情页主图',
        accept: 'image/png, image/gif, image/jpg, image/jpeg',
        limit: 5,
        type: 2,
        isImage: true
      },
      // 商品详情视频
      detailVideoObj: {
        label: '详情页视频',
        accept: 'video/mp4',
        limit: 1,
        type: 4,
        isImage: false
      },
      // 首页图片
      homePicObj: {
        label: '首页主图',
        accept: 'image/png, image/gif, image/jpg, image/jpeg',
        limit: 1,
        type: 3,
        isImage: true
      },
      // 商品类型
      typeOptions: this.commodityType,
      // 商品产地
      productAddressOptions: [],
      // 商品状态
      statusOptions: [
        {
          value: 0,
          label: '下架'
        },
        {
          value: 1,
          label: '上架'
        }
      ],
      // 正则
      rules: {
        name: [{ required: true, message: '输入商品名称', trigger: 'blur' }],
        productAddress: [{ required: true, message: '输入商品产地', trigger: 'blur' }],
        recommend: [{ required: true, message: '输入推荐理由', trigger: 'blur' }],
        type: [
          { required: true, message: '选择商品类型', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '输入商品介绍', trigger: 'blur' }
        ],
        markPrice: [
          { required: true, message: '输入标价', trigger: 'blur' },
          { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: '输入两位小数', trigger: 'blur' }
        ],
        actualPrice: [
          { required: true, message: '输入实际价格', trigger: 'blur' },
          { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: '输入两位小数', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '输入库存', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '库存必须为数字值', trigger: 'blur' }
        ],
        sales:  [
          { required: true, message: '输入销量数', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '销量必须为数字值', trigger: 'blur' }
        ],
        noVipRakeBack: [
          {required: true, message: '输入返佣金额', trigger: 'blur'},
          {pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: '输入两位小数', trigger: 'blur' }

        ],
        selfPurchase: [
          {required: true, message: '输入自购省比例', trigger: 'blur'},
          { pattern: /(^0\.[0-9][1-9]$)|(^0\.[1-9]$)|(^0$)|(^1$)/, message: '输入小于1的两位小数', trigger: 'blur' }
        ]
      },
      isUpdate: false,
      mainPic: [],
      detailPic: [],
      homePic: [],
      detailVideo: []
    }
  },
  watch: {
    // 监听数据变化
    row() {
      this.isUpdate = false
      this.onGetRow()
    }
  },
  created() {
    // 初始化
    this.defaultForm = JSON.parse(JSON.stringify(this.ruleForm))
    // 取默认 只触发一次
    this.onGetRow()
  },
  methods: {
    // 编辑时 取默认值
    onGetRow() {
      this.mainPic = []
      this.detailPic = []
      if (JSON.stringify(this.row) !== '{}') {
        this.ruleForm = {
          id: this.row.id,
          name: this.row.name,
          productAddress: this.row.productAddress == 0 ? '' : this.row.productAddress,
          type: this.row.type,
          upperShelfFlag: this.row.upperShelfFlag,
          introduce: this.row.introduce,
          detailsIntroduce: this.row.detailsIntroduce,
          mainPic: this.row.mainPic,
          detailPic: this.row.detailPic,
          homePic: this.row.homePic,
          detailVideo: this.row.detailVideo,
          markPrice: this.row.markPrice,
          actualPrice: this.row.actualPrice,
          stock: this.row.stock,
          sales: this.row.sales,
          noVipRakeBack: this.row.noVipRakeBack,
          selfPurchase: this.row.selfPurchase,
          recommend: this.row.recommend
        }
        // 下载详情图片
        let _resultPic = this.row.detailPic.split(',')
        _resultPic.forEach(pic => {
          getDownUrl({
            fileName: pic
          }).then(res => {
            this.detailPic.push({ name: pic, url: res.data.url.split("?")[0] })
          })
        })
        // 下载商品主图
        getDownUrl({
          fileName: this.row.mainPic
        }).then(res => {
           this.mainPic.push({ name: this.row.detailPic, url: res.data.url.split("?")[0] })
        })
        // 首页图片
        getDownUrl({
          fileName: this.row.homePic
        }).then(res => {
           this.homePic.push({ name: this.row.homePic, url: res.data.url.split("?")[0] })
        })
        // 详情视频
        getDownUrl({
          fileName: this.row.detailVideo
        }).then(res => {
           this.detailVideo.push({ name: this.row.detailVideo, url: res.data.url.split("?")[0] })
        })
      }
    },
    // 赋值富文本
    onGetEditorValue(data) {
      this.isUpdate = true
      this.ruleForm.detailsIntroduce = data
    },
    // 子组件传值
    onChangeImageKey(fileName, type, isDetele, url) {
      if (isDetele) {
        if (type === 2) {
          if (this.ruleForm.detailPic.indexOf(',') === 0) {
            this.ruleForm.detailPic = this.ruleForm.detailPic.substr(1).split(',').filter(value => value !== fileName).join(',')
          } else {
            this.ruleForm.detailPic = this.ruleForm.detailPic.split(',').filter(value => value !== fileName).join(',')
          }
          this.detailPic = this.detailPic.filter(item => item.name !== fileName)
        } else if (type === 1){
          this.ruleForm.mainPic = fileName
          this.mainPic = this.mainPic.filter(item => item.name !== fileName)
        } else if (type === 4){
          this.ruleForm.detailVideo = fileName
          this.detailVideo = this.detailVideo.filter(item => item.name !== fileName)
        } else {
          this.ruleForm.homePic = fileName
          this.homePic = this.homePic.filter(item => item.name !== fileName)
        }
      } else {
        if (type === 1) {
          this.ruleForm.mainPic = fileName
          if (url) {
            this.mainPic.push({name: fileName, url: url})
          }
        } else if (type === 2) {
          this.ruleForm.detailPic += ',' + fileName
          if (url) {
            this.detailPic.push({name: fileName, url: url})
          }
        } else if (type === 3) {
          this.ruleForm.homePic = fileName
          if (url) {
            this.homePic.push({name: fileName, url: url})
          }
        } else if (type === 4) {
          this.ruleForm.detailVideo = fileName
          if (url) {
            this.detailVideo.push({name: fileName, url: url})
          }
        }
      }
    },
    // 提交
    onSubmitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.ruleForm.mainPic === '' || this.ruleForm.detailPic === '' || this.ruleForm.homePic === '') {
            this.$message.error('请上传图片')
            return false
          }
          if (this.ruleForm.detailPic.indexOf(',') === 0) {
            this.ruleForm.detailPic = this.ruleForm.detailPic.substr(1)
          }
          if (this.ruleForm.id) {
            // 编辑
            getProductUpdate(this.ruleForm).then(res => {
              this.ruleForm = JSON.parse(JSON.stringify(this.defaultForm))
              this.$emit('onCancelBtn', { isShow: false, isRefresh: true })
              this.$message({
                message: '编辑商品成功',
                type: 'success'
              })
            })
          } else {
            // 新增
            getProductAdd(this.ruleForm).then(res => {
              this.ruleForm = JSON.parse(JSON.stringify(this.defaultForm))
              this.$emit('onCancelBtn', { isShow: false, isRefresh: true })
              this.$message({
                message: '新增商品成功',
                type: 'success'
              })
            })
          }
        }
      })
    },
    // 取消
    onCancelForm(formName) {
      this.$refs[formName].resetFields()
      this.ruleForm = JSON.parse(JSON.stringify(this.defaultForm))
      this.$emit('onCancelBtn',{ isShow: false, isRefresh: false })
    }
  }
}
</script>

 <style lang="scss">
.commodity-details {
  @include column;
  height: 100%;
  position: relative;
  .commodity-details__wrapper {
    overflow: hidden;
    display: flex;
    .commodity-details__row {
      width: 100%;
      @include row;
      justify-content: space-between;
      .el-form-item {
        flex: 1!important;
      }
    }
    .el-form__details {
      width: 50%;
      height: 100%;
      @include column;
      .el-select {
        width: 100%;
      }
    }
    .el-form__quill {
      flex: 1;
      height: 100%;
    }
  }
  .commodity-details__btns {
    padding-top: 10px;
    box-shadow: 0 -2px 2px #ececec;
  }
}
</style>
